import 'dart:math' as math;

import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

var itemJson = {
  "image": "assets/images/my1.png",
  "addNum": 1,
  "time": "2022-03-01 12:00:00",
  "music": "音效1",
  "context": ""
};

var historyItems = [];

int initHistory() {
  // 生成随机数整数
  int random = math.Random().nextInt(30);

  for (int i = 0; i < random; i++) {
    historyItems.add(itemJson);
  }

  print(historyItems);
  return random;
}

getHistoryList() {
  var list = [];
  for (int i = 0; i < 10; i++) {
    list.add(itemJson);
  }
  return list;
}

class MuYuPage extends StatefulWidget {
  const MuYuPage({super.key});

  @override
  State<MuYuPage> createState() => _MuYuPage();
}

class _MuYuPage extends State<MuYuPage> {
  // 功德数
  int counter = 0;
  // 当前随机功德数
  int actCounter = 0;

  final List<ImageOption> imageOptions = const [
    ImageOption('基础版', 'assets/images/my1.png', 1, 3, '1'),
    ImageOption('尊享版', 'assets/images/my2.png', 3, 6, '2'),
  ];

  final List<AudioOption> audioOptions = const [
    AudioOption('音效1', '1'),
    AudioOption('音效2', '2'),
    AudioOption('音效3', '3'),
  ];

  // 木鱼当前被选择
  int _activeImageIndex = 0;
  // 木鱼声音当前被选择
  int _activeAudioIndex = 0;

  // 木鱼类型
  String picture = '1';
  // 木鱼声音
  String music = '1';

  AudioPool? pool;

  final ButtonStyle style = ElevatedButton.styleFrom(
    minimumSize: const Size(36, 36), // 最小尺寸
    padding: EdgeInsets.zero, // 边距
    backgroundColor: Colors.green, // 背景色
    elevation: 0, // 阴影深度
  );

  @override
  void initState() {
    super.initState();
    counter = initHistory();
    _initAudioPool();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('电子木鱼'),
          actions: [
            IconButton(
              onPressed: () => {Navigator.pushNamed(context, 'RecordOfMerit')},
              icon: const Icon(Icons.history),
            )
          ],
        ),
        body: Stack(
          children: [
            Container(
                color: const Color.fromARGB(237, 242, 250, 255),
                child: Column(
                  children: [
                    Expanded(
                      child: Center(
                        child: Text(
                          "功德数：$counter",
                          style: const TextStyle(
                              color: Colors.black, fontSize: 25),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                          color: const Color.fromARGB(237, 242, 250, 255),
                          child: Column(children: [
                            if (actCounter != 0)
                              AnimateText(text: '"功德+$actCounter"'),
                            Center(
                                child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                // 设置背景色
                                backgroundColor:
                                    const Color.fromARGB(237, 242, 250, 255),
                                // 设置阴影
                                elevation: 0,
                                // 设置圆角
                                shape: const RoundedRectangleBorder(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(360))),
                              ),
                              onPressed: () {
                                addCounter();
                              },
                              child: Image.asset(
                                'assets/images/my$picture.png',
                                width: 200,
                              ),
                            )),
                          ])),
                    ),
                  ],
                )),
            // 右上角按钮
            Positioned(
                right: 10,
                top: 10,
                child: Wrap(
                  spacing: 8,
                  direction: Axis.vertical,
                  children: [
                    ElevatedButton(
                      style: style,
                      onPressed: musicClick,
                      child: const Icon(Icons.music_note_outlined),
                    ),
                    ElevatedButton(
                      style: style,
                      onPressed: imageClick,
                      child: const Icon(Icons.image),
                    )
                  ],
                )),
          ],
        ));
  }

  _onTapSwitchMusic(int value) {
    Navigator.of(context).pop();
    if (value == _activeAudioIndex) return;
    setState(() {
      _activeAudioIndex = value;
      music = audioOptions[_activeAudioIndex].src;
    });
    // 重新加载音乐
    _initAudioPool();
  }

  void musicClick() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return AudioOptionPanel(
          audioOptions: audioOptions,
          activeIndex: _activeAudioIndex,
          onSelect: _onTapSwitchMusic,
        );
      },
    );
  }

  void _onTapSwitchImage(int value) {
    Navigator.of(context).pop();
    if (value == _activeImageIndex) return;
    setState(() {
      _activeImageIndex = value;
      picture = imageOptions[_activeImageIndex].picture;
    });
  }

  void imageClick() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return ImageOptionPanel(
          imageOptions: imageOptions,
          activeIndex: _activeImageIndex,
          onSelect: _onTapSwitchImage,
        );
      },
    );
  }

  void addCounter() {
    int addMin = imageOptions[_activeImageIndex].min;
    int addMax = imageOptions[_activeImageIndex].max + 1 - addMin;
    actCounter = math.Random().nextInt(addMax) + addMin;
    setState(() {
      counter += actCounter;
    });
    pool?.start();
    historyItems.insert(0, {
      "image": "assets/images/my$picture.png",
      "addNum": actCounter,
      "time": DateTime.now().toString(), //当前时间
      "music": "音效$music",
      "context": ""
    });
  }

  // 加载音乐
  void _initAudioPool() async {
    pool = await FlameAudio.createPool(
      'assets/audio/my$music.mp3',
      maxPlayers: 1,
    );
  }
}

class ImageOptionPanel extends StatelessWidget {
  final List<ImageOption> imageOptions;
  final ValueChanged<int> onSelect;
  final int activeIndex;

  const ImageOptionPanel({
    super.key,
    required this.imageOptions,
    required this.activeIndex,
    required this.onSelect,
  });

  @override
  Widget build(BuildContext context) {
    const TextStyle labelStyle =
        TextStyle(fontSize: 16, fontWeight: FontWeight.bold);
    const EdgeInsets padding =
        EdgeInsets.symmetric(horizontal: 8.0, vertical: 16);
    return Material(
      child: SizedBox(
        height: 300,
        child: Column(
          children: [
            Container(
                height: 46,
                alignment: Alignment.center,
                child: const Text("选择木鱼", style: labelStyle)),
            Expanded(
                child: Padding(
              padding: padding,
              child: Row(
                children: [
                  Expanded(child: _buildByIndex(0)),
                  const SizedBox(width: 10),
                  Expanded(child: _buildByIndex(1)),
                ],
              ),
            ))
          ],
        ),
      ),
    );
  }

  Widget _buildByIndex(int index) {
    bool active = index == activeIndex;
    return GestureDetector(
      onTap: () => onSelect(index),
      child: ImageOptionItem(
        option: imageOptions[index],
        active: active,
      ),
    );
  }
}

class ImageOption {
  final String name; // 名称
  final String src; // 资源
  final int min; // 每次点击时功德最小值
  final int max; // 每次点击时功德最大值
  final String picture;

  const ImageOption(this.name, this.src, this.min, this.max, this.picture);
}

class AudioOption {
  final String name; // 名称
  final String src; // 资源

  const AudioOption(this.name, this.src);
}

class ImageOptionItem extends StatelessWidget {
  final ImageOption option;
  final bool active;

  const ImageOptionItem({
    super.key,
    required this.option,
    required this.active,
  });

  @override
  Widget build(BuildContext context) {
    const Border activeBorder =
        Border.fromBorderSide(BorderSide(color: Colors.blue));
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: !active ? null : activeBorder,
      ),
      child: Column(
        children: [
          Text(option.name,
              style: const TextStyle(fontWeight: FontWeight.bold)),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Image.asset(option.src),
            ),
          ),
          Text('每次功德 +${option.min}~${option.max}',
              style: const TextStyle(color: Colors.grey, fontSize: 12)),
        ],
      ),
    );
  }
}

class AnimateText extends StatefulWidget {
  final String text;

  const AnimateText({super.key, required this.text});

  @override
  State<AnimateText> createState() => _FadTextState();
}

class _FadTextState extends State<AnimateText>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> opacity;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 500));
    opacity = Tween(begin: 1.0, end: 0.0).animate(controller); // tag1
    controller.forward();
  }

  @override
  void didUpdateWidget(covariant AnimateText oldWidget) {
    super.didUpdateWidget(oldWidget);
    controller.forward(from: 0);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: opacity,
      child: Text(widget.text),
    );
  }
}

class AudioOptionPanel extends StatelessWidget {
  final List<AudioOption> audioOptions;
  final ValueChanged<int> onSelect;
  final int activeIndex;

  const AudioOptionPanel({
    super.key,
    required this.audioOptions,
    required this.activeIndex,
    required this.onSelect,
  });

  @override
  Widget build(BuildContext context) {
    const TextStyle labelStyle =
        TextStyle(fontSize: 16, fontWeight: FontWeight.bold);
    return Material(
      child: SizedBox(
        height: 300,
        child: Column(
          children: [
            Container(
                height: 46,
                alignment: Alignment.center,
                child: const Text(
                  "选择音效",
                  style: labelStyle,
                )),
            ...List.generate(audioOptions.length, _buildByIndex)
          ],
        ),
      ),
    );
  }

  Widget _buildByIndex(int index) {
    bool active = index == activeIndex;
    return ListTile(
      selected: active,
      onTap: () => onSelect(index),
      title: Text(audioOptions[index].name),
      trailing: IconButton(
        splashRadius: 20,
        onPressed: () => _tempPlay(audioOptions[index].src),
        icon: const Icon(
          Icons.record_voice_over_rounded,
          color: Colors.blue,
        ),
      ),
    );
  }

  void _tempPlay(String src) async {
    AudioPool pool = await FlameAudio.createPool(src, maxPlayers: 1);
    pool.start();
  }
}

// 功德记录详情页
class RecordOfMerit extends StatefulWidget {
  const RecordOfMerit({super.key});

  @override
  State<RecordOfMerit> createState() => _RecordOfMerit();
}

class _RecordOfMerit extends State<RecordOfMerit> {
  static const loadingTag = "##loading##"; //表尾标记
  final _words = <Object>[loadingTag];

  @override
  void initState() {
    super.initState();
    setState(() {
      _words.insertAll(_words.length - 1, [...historyItems]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('功德记录'),
        ),
        body: Container(
            color: const Color.fromARGB(255, 248, 248, 248),
            child: ListView.separated(
              itemCount: _words.length,
              itemBuilder: (context, index) {
                //如果到了表尾
                if (_words[index] == loadingTag) {
                  //不足100条，继续获取数据
                  if (_words.length - 1 < 200) {
                    //获取数据
                    _retrieveData();
                    //加载时显示loading
                    return Container(
                      padding: const EdgeInsets.all(16.0),
                      alignment: Alignment.center,
                      color: const Color.fromARGB(255, 248, 248, 248),
                      child: const SizedBox(
                        width: 24.0,
                        height: 24.0,
                        child: CircularProgressIndicator(strokeWidth: 2.0),
                      ),
                    );
                  } else {
                    //已经加载了100条数据，不再获取数据。
                    return Container(
                      alignment: Alignment.center,
                      color: const Color.fromARGB(255, 248, 248, 248),
                      padding: const EdgeInsets.all(16.0),
                      child: const Text(
                        "没有更多了",
                        style: TextStyle(color: Colors.grey),
                      ),
                    );
                  }
                }
                return Container(
                    color: const Color.fromARGB(255, 248, 248, 248),
                    child: buildItem(context, index, _words[index]));
              },
              separatorBuilder: (context, index) => const Divider(height: .0),
            )));
  }

  Widget buildItem(context, index, item) {
    String image = '';
    String musicStr = '';
    String addNum = '';
    String time = '';
    if (item != null) {
      if (item.containsKey('image')) image = item['image'];
      if (item.containsKey('music')) musicStr = item['music'];
      if (item.containsKey('addNum')) addNum = item['addNum'].toString();
      if (item.containsKey('time')) time = item['time'];
    }
    return Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                  mainAxisAlignment: MainAxisAlignment.start, // 对齐
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 0, 10, 0),
                      child: Image.asset(
                        image,
                        width: 40.0,
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start, // 确保左对齐
                      children: [
                        Text(
                          "功德+$addNum",
                          style: const TextStyle(
                              color: Colors.black, fontSize: 16),
                        ),
                        Text(
                          musicStr,
                          style: const TextStyle(
                              color: Color.fromARGB(255, 105, 105, 105),
                              fontSize: 14),
                        ),
                      ],
                    ),
                  ]),
              Text(
                time,
                style: const TextStyle(
                    color: Color.fromARGB(255, 105, 105, 105), fontSize: 12),
              )
            ]));
  }

  void _retrieveData() {
    Future.delayed(const Duration(seconds: 2)).then((e) {
      setState(() {
        // 每次生成10条数据
        _words.insertAll(_words.length - 1, [...getHistoryList()]);
      });
    });
  }
}
